const express = require('express');
const app = express();
const request = require('request');
const bodyParser = require('body-parser');

//设置跨域访问
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type, Accept, requestRepeatId");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", " 3.2.1");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

// 使用bodyParser 中间件来解析
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//let urlPrefix = 'http://test2.lejiayun.com'; //地址前缀

let urlPrefix = 'https://sos.lacesar.com';

// GET 请求
app.get("/*", (req, res) => {
    let url = urlPrefix + req.url;

    if(req.url.indexOf('/ws/geocoder/v1/') > -1){
        url = 'https://apis.map.qq.com' + req.url; // 腾讯地图地址前缀
    }
    
    request({ 
        url,
        headers: {
            "Content-Type": "application/json",
            // 'Authorization': req.headers.authorization
        },
        qs: req.query
    }, (err, dataRes) => {
        if(err){
            return res.json({err}); 
        }
        return res.json(JSON.parse(dataRes.body));
    })
});

// POST 请求
app.post("/*", (req, res) => {
    
    request({
        url: urlPrefix + req.url,
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            // "Authorization": req.headers.authorization,
            // 'requestRepeatId': req.headers.requestrepeatid
        }, 
        body: JSON.stringify(req.body)
    }, function(err, dataRes) {
        if(err){
            return res.json({err});
        }
        return res.json(JSON.parse(dataRes.body));
    });

});


//配置服务端口
app.listen(9000, function () {
    console.log('9000端口启动成功');
});